//
//  SEGWebViewLoadManager.m
//  TWebKit
//
//  Created by 山刘 on 2018/11/14.
//  Copyright © 2018年 山刘. All rights reserved.
//
#if __has_include(<Commom/SEGPlatformManager.h>)
#import <Commom/SEGPlatformManager.h>
#else
#import "SEGPlatformManager.h"
#endif

#if __has_include(<SEGPlatform/SEGBussinessConstHeader.h>)
#import <SEGPlatform/SEGBussinessConstHeader.h>
#else
#import "SEGBussinessConstHeader.h"
#endif

#import "SEGWebViewLoadManager.h"
#import "SEGUrlparamsModel.h"
@implementation SEGWebViewLoadManager

static id _webViewLoadManager;
+(instancetype)sharedManager{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _webViewLoadManager = [[self alloc]init];
    });
    return _webViewLoadManager;
}



/**
 通过传入的url地址生成JavaScript字符串
 
 @param urlString 格式：{"para":["userId","accessToken","deviceId","communityId","source","versionCode"],"fn":"uhomeNativeApi.getUserInfoCb"}
 @return js注入函数：uhomeNativeApi.getUserInfoCb({"deviceId":"B56D14B7-D3E8-492E-9D2D-8AE484FF64B7","source":"2","userId":"452613","communityId":"67"})
 */
-(NSString*)segJavaScriptStringFromUrlStringV2:(NSString*)urlString{
    if (!(urlString && [urlString isKindOfClass:[NSString class]] && urlString.length > 0)) return nil;
    
    SEGUrlparamsModel * data = [SEGUrlparamsModel yy_modelWithJSON:urlString];
    if (!(data && data.para && data.para.count > 0)) return nil;
    
    NSMutableDictionary *ret = [NSMutableDictionary dictionary];
    
    if ([data.para containsObject:@"userId"]) [ret setObject: ([[self.params allKeys] containsObject:@"userId"] ? [self.params valueForKey:@"userId"] : @"")  forKey:@"userId"];
    if ([data.para containsObject:@"desc"]) [ret setObject:([[self.params allKeys] containsObject:@"desc"] ? [self.params valueForKey:@"desc"] : @"") forKey:@"desc"];
    if ([data.para containsObject:@"isDoor"]) [ret setObject:([[self.params allKeys] containsObject:@"isDoor"] ? [self.params valueForKey:@"isDoor"] : @"") forKey:@"isDoor"];
    if ([data.para containsObject:@"houseList"]) [ret setObject:([[self.params allKeys] containsObject:@"houseList"] ? [self.params valueForKey:@"houseList"] : @"") forKey:@"houseList"];
    if ([data.para containsObject:@"isCommunitySignExpress"]) [ret setObject:([[self.params allKeys] containsObject:@"isCommunitySignExpress"] ? [self.params valueForKey:@"isCommunitySignExpress"] : @"") forKey:@"isCommunitySignExpress"];
    if ([data.para containsObject:@"sendExpressServiceTel"]) [ret setObject:([[self.params allKeys] containsObject:@"sendExpressServiceTel"] ? [self.params valueForKey:@"sendExpressServiceTel"] : @"") forKey:@"sendExpressServiceTel"];
    if ([data.para containsObject:@"communityId"]) [ret setObject:([[self.params allKeys] containsObject:@"communityId"] ? [self.params valueForKey:@"communityId"] : @"") forKey:@"communityId"];
    if ([data.para containsObject:@"nickname"]) [ret setObject:([[self.params allKeys] containsObject:@"nickname"] ? [self.params valueForKey:@"nickname"] : @"") forKey:@"nickname"];
    
    if ([data.para containsObject:@"systemVersionCode"]) [ret setObject:[UIDevice currentDevice].systemVersion forKey:@"systemVersionCode"];
    if ([data.para containsObject:@"systemName"]) [ret setObject:[UIDevice currentDevice].systemName forKey:@"systemName"];
    if ([data.para containsObject:@"versionCode"]) [ret setObject:([[self.params allKeys] containsObject:@"versionCode"] ? [self.params valueForKey:@"versionCode"] : @"") forKey:@"versionCode"];
    if ([data.para containsObject:@"phoneModel"]) [ret setObject:([[self.params allKeys] containsObject:@"phoneModel"] ? [self.params valueForKey:@"phoneModel"] : @"") forKey:@"phoneModel"];
    if ([data.para containsObject:@"source"]) [ret setObject:([[self.params allKeys] containsObject:@"source"] ? [self.params valueForKey:@"source"] : @"") forKey:@"source"];
    if ([data.para containsObject:@"deviceId"]) [ret setObject:([[self.params allKeys] containsObject:@"deviceId"] ? [self.params valueForKey:@"deviceId"] : @"") forKey:@"deviceId"];
    if ([data.para containsObject:@"wxAppId"]) [ret setObject:kWeChatAppId forKey:@"wxAppId"];
    
//    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
//    [dict setObject:@"0" forKey:@"code"];
//    [dict setObject:@"" forKey:@"message"];
//    [dict setObject:[ret yy_modelToJSONString] forKey:@"data"];
    
    return [NSString stringWithFormat:@"%@(%@)",data.fn,[ret yy_modelToJSONString]];
}

/**
 通过传入的url地址生成JavaScript字符串
 
 @param urlString 格式：{"para":["userId","accessToken","deviceId","communityId","source","versionCode"],"fn":"uhomeNativeApi.getUserInfoCb"}
 @return js注入函数：uhomeNativeApi.getUserInfoCb({"deviceId":"B56D14B7-D3E8-492E-9D2D-8AE484FF64B7","source":"2","userId":"452613","communityId":"67"})
 */
+(NSString*)segJavaScriptStringFromUrlString:(NSString*)urlString{
    if (!(urlString && [urlString isKindOfClass:[NSString class]] && urlString.length > 0)) return nil;
    
    SEGUrlparamsModel * data = [SEGUrlparamsModel yy_modelWithJSON:urlString];
    if (!(data && data.para && data.para.count > 0)) return nil;
    
    NSMutableDictionary *ret = [NSMutableDictionary dictionary];
    
    SEGProfileModel * profile = [SEGProfileManager sharedManager].profile;
    
    if ([data.para containsObject:@"userId"]) [ret setObject: profile.userId forKey:@"userId"];
    if ([data.para containsObject:@"desc"]) [ret setObject:profile.desc forKey:@"desc"];
    if ([data.para containsObject:@"isDoor"]) [ret setObject:profile.isDoor forKey:@"isDoor"];
    if ([data.para containsObject:@"houseList"]) [ret setObject:profile.houseName forKey:@"houseList"];
    if ([data.para containsObject:@"isCommunitySignExpress"]) [ret setObject:profile.isCommunitySignExpress forKey:@"isCommunitySignExpress"];
    if ([data.para containsObject:@"sendExpressServiceTel"]) [ret setObject:profile.sendExpressServiceTel forKey:@"sendExpressServiceTel"];
    if ([data.para containsObject:@"communityId"]) [ret setObject:profile.jobCommunity forKey:@"communityId"];
    if ([data.para containsObject:@"nickname"]) [ret setObject:profile.nickname forKey:@"nickname"];
    
    if ([data.para containsObject:@"systemVersionCode"]) [ret setObject:[UIDevice currentDevice].systemVersion forKey:@"systemVersionCode"];
    if ([data.para containsObject:@"systemName"]) [ret setObject:[UIDevice currentDevice].systemName forKey:@"systemName"];
//    if ([data.para containsObject:@"versionCode"]) [ret setObject:[SEGServerManager getClientVersionCode] forKey:@"versionCode"];
    if ([data.para containsObject:@"phoneModel"]) [ret setObject:[UIDevice currentDevice].machineModelName forKey:@"phoneModel"];
    if ([data.para containsObject:@"source"]) [ret setObject:[SEGServerManager getClientSourceType] forKey:@"source"];
    if ([data.para containsObject:@"deviceId"]) [ret setObject:[SEGCKeyChainStore stringWithUUIDStringInKeyChainStore] forKey:@"deviceId"];
    if ([data.para containsObject:@"wxAppId"]) [ret setObject:kWeChatAppId forKey:@"wxAppId"];
    if ([data.para containsObject:@"tel"]) [ret setObject:profile.tel forKey:@"tel"];
    if ([data.para containsObject:@"custId"]) [ret setObject:profile.custId forKey:@"custId"];
    if ([data.para containsObject:@"statusBarHeight"]) [ret setObject:@(LYStatusBarHeight()) forKey:@"statusBarHeight"];
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:@"1" forKey:@"code"];
    [dict setObject:@"" forKey:@"message"];
    [dict setObject:ret forKey:@"data"];

    return [NSString stringWithFormat:@"%@(%@)",data.fn,[dict yy_modelToJSONString]];
}



/**
 对url地址进行业务参数替换

 @param urlString 服务器下发的url地址:parking/index.html?token=segi_token&deviceid=segi_deviceid&version=segi_version
 @return 参数替换后的url地址:parking/index.html?token=2222&deviceid=B56D14B7-D3E8-492E-9D2D-8AE484FF64B7&version=4.6.0
 */
+(NSString*)segReplaceUrlStringWithUrlString:(NSString*)urlString{
    
    SEGProfileModel * profile = [SEGProfileManager sharedManager].profile;
    
    if ([urlString rangeOfString:@"segi_cy"].location != NSNotFound) urlString = [urlString stringByReplacingOccurrencesOfString:@"segi_cy" withString:profile.city];
    if ([urlString rangeOfString:@"segi_region"].location != NSNotFound) urlString = [urlString stringByReplacingOccurrencesOfString:@"segi_region" withString:profile.region];
    if ([urlString rangeOfString:@"segi_pr"].location != NSNotFound) urlString = [urlString stringByReplacingOccurrencesOfString:@"segi_pr" withString:profile.province];
    if ([urlString rangeOfString:@"segi_address"].location != NSNotFound) urlString = [urlString stringByReplacingOccurrencesOfString:@"segi_address" withString:profile.houseName];
    if ([urlString rangeOfString:@"segi_houseId"].location != NSNotFound) urlString = [urlString stringByReplacingOccurrencesOfString:@"segi_houseId" withString:profile.houseId];
    if ([urlString rangeOfString:@"segi_cid"].location != NSNotFound) urlString = [urlString stringByReplacingOccurrencesOfString:@"segi_cid" withString:profile.jobCommunity];
    if ([urlString rangeOfString:@"segi_tel"].location != NSNotFound) urlString = [urlString stringByReplacingOccurrencesOfString:@"segi_tel" withString:profile.tel];
    if ([urlString rangeOfString:@"segi_userid"].location != NSNotFound) urlString = [urlString stringByReplacingOccurrencesOfString:@"segi_userid" withString:profile.userId];
    if ([urlString rangeOfString:@"segi_custid"].location != NSNotFound) urlString = [urlString stringByReplacingOccurrencesOfString:@"segi_custid" withString:profile.custId];
    if ([urlString rangeOfString:@"segi_nickname"].location != NSNotFound) urlString = [urlString stringByReplacingOccurrencesOfString:@"segi_nickname" withString:profile.nickname];
    if ([urlString rangeOfString:@"segi_version"].location != NSNotFound) urlString = [urlString stringByReplacingOccurrencesOfString:@"segi_version" withString:[SEGServerManager getClientVersionCode]];
    if ([urlString rangeOfString:@"segi_carno"].location != NSNotFound) urlString = [urlString stringByReplacingOccurrencesOfString:@"segi_carno" withString:@""];//车牌号 可传入车牌号码(可选) 暂时没有
    if ([urlString rangeOfString:@"segi_sign"].location != NSNotFound) urlString = [urlString stringByReplacingOccurrencesOfString:@"segi_sign" withString:[self segSignWithTel:profile.tel]];
    if ([urlString rangeOfString:@"segi_deviceid"].location != NSNotFound) urlString = [urlString stringByReplacingOccurrencesOfString:@"segi_deviceid" withString:[SEGCKeyChainStore stringWithUUIDStringInKeyChainStore]];
    if ([urlString rangeOfString:@"segi_versionName"].location != NSNotFound) {
        NSString * version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
        urlString = [urlString stringByReplacingOccurrencesOfString:@"segi_versionName" withString:version];
    }
        
    return urlString;
}

/**
 险萝卜签名密文替换
 替换格式：MD5(手机号|密钥)

 @param tel 用户电话号码
 @return MD5加密结果
 */
+(NSString*)segSignWithTel:(NSString*)tel{
    return [[NSString stringWithFormat:@"%@|%@", tel, @"kmbF8tE2rgHkTRrd7pn9WKTAHUukKjcn"] md5String];
}

//获取本地路径
+ (NSString *)getLocalPathByPath:(NSString *)path
{
    NSString *fileCacheDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES).firstObject stringByAppendingPathComponent:@"UhomeFileDirectory"];
    //创建文件夹
    if (![self seg_creatFileDirectoryWith:fileCacheDirectory]) {
        //文件夹创建失败
        return @"";
    }
    
    NSArray * stringArr = [path componentsSeparatedByString:@"/"];
    NSString * newPath = stringArr.count==0?path:stringArr.lastObject;
    
    NSString *pathD = fileCacheDirectory;
    NSString* filePath = [NSString stringWithFormat:@"%@/%@", pathD, newPath];
    return filePath;
}

+ (BOOL)seg_creatFileDirectoryWith:(NSString *)dirPath{
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    // fileExistsAtPath 判断一个文件或目录是否有效，isDirectory判断是否一个目录
    BOOL isDir = NO;
    BOOL existed = [fileManager fileExistsAtPath:dirPath isDirectory:&isDir];
    //如果文件夹不存在
    if (!(isDir == YES && existed == YES)){
        BOOL creatSuccess = [fileManager createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:nil];
        return creatSuccess;
    }
    //如果存在直接返回YES
    return YES;
}


@end
